# -*- coding: utf-8 -*- 
"""
Created by hcx on 17-7-19 下午2:38.
@author: 胡超翔
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import logging

from django.contrib import messages
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.urls import reverse
from django.urls import reverse_lazy
from django.views.generic import FormView
from django.views.generic import RedirectView

from autodeploy.apps.user.forms import LoginForm

logger = logging.getLogger(__name__)


class LoginView(FormView):
    form_class = LoginForm
    template_name = 'user/login.html'
    
    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, locals())
    
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            # 获取用户名,密码
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # 验证登录
            user = validate_login(request, username, password)
            if user.id:
                return redirect(request.GET.get('next', reverse('index:index')))
            else:
                messages.error(request, u'用户名或密码错误')
        else:
            messages.error(request, u'数据验证失败')
        
        return render(request, self.template_name, locals())


class LogoutView(LoginRequiredMixin, RedirectView):
    """后台登出"""
    permanent = False
    query_string = True  # 是否将GET 的查询字符串一起传递给新的地址
    pattern_name = 'user:login'  # 重定向的目标URL 模式的名称
    
    def get_redirect_url(self, *args, **kwargs):
        # 用户注销
        logout(self.request)
        return super(LogoutView, self).get_redirect_url(*args, **kwargs)


def validate_login(request, username, password):
    """验证用户登录"""
    # 验证用户名密码，并返回一个 user对象
    user = authenticate(username=username, password=password)
    if user:
        # 保持登录用户和后端的连接
        login(request, user)
        # 记录该用户登录成功的日志
        logger.info('%s登录成功' % username)
    else:
        # 用户提示：用户名或密码错误
        user = User()
    return user


class ResetPasswordView(LoginRequiredMixin, FormView):
    """后台密码修改"""
    template_name = 'user/reset_password.html'
    form_class = SetPasswordForm
    success_url = reverse_lazy('user:login')
    
    def get_form_kwargs(self):
        kwargs = super(ResetPasswordView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
    
    def form_valid(self, form):
        user = form.save()
        messages.info(self.request, u'密码修改成功')
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(self.request, user)
        return super(ResetPasswordView, self).form_valid(form)
